<template>
  <div class="dashboard-container">
    <div class="app-container">
      <page-tools>
        <!-- 自定义左侧内容 -->
        <template #slot-left>
          <span>共 19 条记录</span>
        </template>

        <!-- 自定义右侧内容 -->
        <template #slot-right>
          <!-- v-ppwer="import" -->
          <el-button
            v-power="'import'"
            type="danger"
            size="small"
            @click="$router.push('/excel')"
          >导入excel</el-button>
          <el-button
            v-power="'export'"
            type="success"
            size="small"
            @click="downloadExcel"
          >导出excel</el-button>
          <!-- v-power="export" -->
          <el-button
            type="primary"
            size="small"
            :visible.sync="showDialog"
            width="30%"
            @click="showDialog=true"
          >新增员工</el-button>
        </template>
      </page-tools>
      <!-- 员工列表 -->
      <!-- :data="tableData" -->
      <el-card class="box-card">
        <el-table
          border
          style="width: 100%"
          :data="employeeList"
        >
          <!-- type="index根据索引排序 -->
          <el-table-column label="序号" width="60" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像" prop="staffPhoto" width="110">
            <template v-slot="scope">
              <!-- <img :src="scope.row.staffPhoto" alt="" class="staffPhoto"> -->
              <image-holder :src="scope.row.staffPhoto" class="staffPhoto" />
            </template>
          </el-table-column>
          <el-table-column label="手机号" prop="mobile" sortable width="110" />
          <el-table-column label="工号" prop="workNumber" :default-sort="{prop:'workNumber',order:'descending'}" sortable />
          <el-table-column
            label="聘用形式"
            prop="formOfEmployment"
            :formatter="formatter"
          />
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable>
            <template v-slot="scope">
              <span>{{ scope.row.timeOfEntry | formatTime }}</span>
            </template>
          </el-table-column>
          <el-table-column label="转正时间" prop="correctionTime" sortable>
            <template v-slot="scope">
              <span>{{ scope.row.correctionTime | formatTime }}</span>
            </template>
          </el-table-column>
          <el-table-column label="账户状态" />
          <el-table-column label="操作" width="280">
            <template v-slot="scope">
              <el-button type="text" size="small" @click="$router.push('/employees/detail?id=' + scope.row.id)">查看</el-button>
              <el-button type="text" size="small" @click="setRole(scope.row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="delEmployeeFn(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-pagination
          style="margin-top: 10px"
          :current-page="query.page"
          :page-sizes="[5, 15, 20, 30]"
          :page-size="query.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
        <!-- 子组件弹框 -->
        <el-dialog
          title="新增员工"
          :visible.sync="showDialog"
          width="90%"
          @close="closeDialogFn"
        >
          <emp-dialog
            ref="addForm"
            @close="showDialog=false"
            @updateEmployee="updateEmployee"
          />
          <!-- 设置角色组件 -->

        </el-dialog>
        <!-- 设置角色组件弹框 -->
        <el-dialog title="分配角色" :visible="showRoleDialog" @close="cancleDialog">
          <!-- 设置角色组件 -->
          <assign-role
            v-if="showRoleDialog"
            :user-id="userId"
            @close="showRoleDialog = false"
          />
        </el-dialog>
      </el-card>
    </div>
  </div>
</template>

<script>
// 引入api
import { getEmployeeList, delEmployee } from '@/api/employees'
// 引入枚举
import EmployeeEnum from '@/constant/employees'
// 引入子组件
import empDialog from './empDialog'
import AssignRole from './assignRole'

// 引入时间格式化数据
import dayjs from 'dayjs'
export default {
  // 过滤器方法形参是需要格式化的数据
  filters: {
    formatTime(value) {
      return dayjs(value).format('YYYY-MM-DD')
    }
  },
  components: {
    empDialog,
    AssignRole
  },
  data() {
    return {
      query: {
        page: 1, // 页码
        size: 10 // 每页显示条数
      },
      total: 0,
      employeeList: [], // 接收员工列表信息
      showDialog: false, // 弹框状态
      showRoleDialog: false, // 查看角色弹框状态
      userId: ''// 传给子组件的id
    }
  },
  created() {
    this.getEmployeeListFn()
  },

  methods: {
    // 关闭弹框
    closeDialog() {
      this.showRoleDialog = false
    },
    // 分配角色按钮
    setRole(id) {
      this.userId = id
      this.showRoleDialog = true// 点击弹框展开
    },
    // 格式化后端返回的数据满则XLSX插件的要求
    transData(rows) {
      // 定义一份枚举数据
      const map = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      const headerArr = Object.keys(rows[0])
      const header = headerArr.map(item => {
        return map[item]
      })
      const data = rows.map(obj => {
        return Object.values(obj)
      })
      return { header, data }
    }, // 导出excel
    async  downloadExcel() {
      const res = await getEmployeeList(this.query)
      console.log(res)
      const excelObj = this.transData(res.data.rows)
      import('@/vendor/Export2Excel').then(excel => {
        // excel表示导入的模块对象

        excel.export_json_to_excel({
          header: excelObj.header, // 表头 必填
          data: excelObj.data, // 具体数据 必填
          filename: '员工列表', // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx' // 生成的文件类型
        })
      })
    },
    //  清空添加员工表单数据
    closeDialogFn() {
      this.$refs.addForm.resetForm()// 调用子组件方法
    },
    // 子级新增员工事件
    updateEmployee() {
      this.getEmployeeListFn()// 刷新列表
      this.showDialog = false// 隐藏弹框
    },

    cancleDialog() {

    },

    // 删除员工信息
    delEmployeeFn(id) {
      this.$confirm('此操作将永久删除该员工, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        // 删除成功
        const res = await delEmployee(id)
        console.log(res)
        // 如果当前剩一条数据,就自动往前走一页
        if (this.employeeList.length === 1) {
          this.query.page--
          // 没有数据的话,就强制留在第一页吧
          if (this.employeeList.length <= 0) {
            this.query.page = 1
          }
        }
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
        this.getEmployeeListFn()// 刷新员工列表
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 格式化聘用形式
    formatter(row, column, cellValue, index) {
      // 因为未知的状态后台返回的是字符串,用number转成数字型的即可
      const obj = EmployeeEnum.hireType.find(item => item.id === Number(cellValue))
      return obj ? obj.value : '未知'
    },
    async   getEmployeeListFn() {
      const res = await getEmployeeList(this.query)
      console.log(res)
      this.employeeList = res.data.rows
      this.total = res.data.total
    },
    handleSizeChange(newSize) {
      this.query.size = newSize
      this.getEmployeeListFn()// 刷新员工列表
    },
    handleCurrentChange(newPage) {
      this.query.page = newPage
      this.getEmployeeListFn()// 刷新员工列表
    }
  }
}

</script>

<style lang="scss" scoped>
.box-card {
  margin-top: 10px;
}
.staffPhoto{
width: 100px;
height: 100px;
border-radius: 50%;
}
</style>
